/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.ui.dialogs;

import java.util.Arrays;
import java.util.Iterator;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.uml2.uml.Package;

/**
 * 
 */
public class SynchronizeWithGenericElementsDialog extends Dialog{

	private Label synchronizationActionsLabel ;
	private java.util.List<com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction> actionsToBePerformed ;
	
	/**
	 * 
	 * 
	 * @param model 
	 * @param parent 
	 */
	public SynchronizeWithGenericElementsDialog(Shell parent, Package model, java.util.List<com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction> actionsToBePerformed){
		super(parent);
		this.actionsToBePerformed = actionsToBePerformed ;
	}

	@Override
	protected void configureShell(Shell shell) {
		// TODO Auto-generated method stub
		super.configureShell(shell);
		shell.setText("Synchronization with generic elements (according to defined template bindings)") ;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.cea.papyrus.core.ui.dialogs.ElementImportTreeSelectionDialog#buildImportTreeList(org.eclipse.swt.widgets.TreeItem, org.eclipse.uml2.uml.Package)
	 */
	/**
	 * Creates the dialog area
	 * 
	 * @param parent composite
	 * 
	 * @return control
	 */
	protected Control createDialogArea(Composite parent){
		Composite composite = (Composite)super.createDialogArea(parent);
		// Set layout for composite
		GridLayout layout = new GridLayout();
		composite.setLayout(layout);
		synchronizationActionsLabel = new Label(composite,SWT.NONE) ;
		if (actionsToBePerformed.isEmpty()) {
			synchronizationActionsLabel.setText("No synchronizations need to be performed.") ;
		}
		else {
			synchronizationActionsLabel.setText("Synchronizations to be performed: \n\n") ;
			for (Iterator<com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction> i = actionsToBePerformed.iterator() ; i.hasNext() ; ) {
				synchronizationActionsLabel.setText(synchronizationActionsLabel.getText() + ". " + i.next().getText() + "\n") ;
			}
		}
		return composite;
	}

	
	
	@Override
	protected Control createButtonBar(Composite parent) {
		Control c = super.createButtonBar(parent);
//		getButton(IDialogConstants.OK_ID).setEnabled(false) ;
		return c ;
	}
		
	
	@Override
	protected void cancelPressed() {
		// TODO Auto-generated method stub
		super.cancelPressed();
//		this.selectedPackage = null ;
	}



	@Override
	protected void okPressed() {
		// TODO Auto-generated method stub
		super.okPressed();
//		Object o = tree.getSelection()[0].getData() ;
//		this.selectedPackage = (Package)tree.getSelection()[0].getData() ;
	}
	
	public class ExampleLabelProvider 
	extends LabelProvider
	implements ITableLabelProvider {

	// Names of images used to represent checkboxes
	public static final String CHECKED_IMAGE 	= "checked";
	public static final String UNCHECKED_IMAGE  = "unchecked";

	// For the checkbox images
//	private static ImageRegistry imageRegistry = new ImageRegistry();

	/**
	 * Note: An image registry owns all of the image objects registered with it,
	 * and automatically disposes of them the SWT Display is disposed.
	 */ 
//	static {
//		String iconPath = "icons/"; 
//		imageRegistry.put(CHECKED_IMAGE, ImageDescriptor.createFromFile(
//				TableViewerExample.class, 
//				iconPath + CHECKED_IMAGE + ".gif"
//				)
//			);
//		imageRegistry.put(UNCHECKED_IMAGE, ImageDescriptor.createFromFile(
//				TableViewerExample.class, 
//				iconPath + UNCHECKED_IMAGE + ".gif"
//				)
//			);	
//	}
	
	/**
	 * Returns the image with the given key, or <code>null</code> if not found.
	 */
	private Image getImage(boolean isSelected) {
//		String key = isSelected ? CHECKED_IMAGE : UNCHECKED_IMAGE;
//		return  imageRegistry.get(key);
		return null ;
	}

	/**
	 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
	 */
	public String getColumnText(Object element, int columnIndex) {
		String result = "";
		com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction action = (com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction) element;
		switch (columnIndex) {
			case 0:  // COMPLETED_COLUMN
				break;
			case 1 :
				result = action.getActionKindText();
				break;
			case 2 :
				result = action.getOriginalFeatureText();
				break;
			case 3 :
				result = action.getOriginalFeatureText();
				break;
			default :
				break; 	
		}
		return result;
	}

	/**
	 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
	 */
	public Image getColumnImage(Object element, int columnIndex) {
//		return (columnIndex == 0) ?   // COMPLETED_COLUMN?
//			getImage(((ExampleTask) element).isCompleted()) :
//			null;
		return null ;
	}

}
	
	public class TableViewerExample {
		/**
			 * @param parent
			 */
			public TableViewerExample(Composite parent, java.util.List<com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction> actionList) {				
				this.addChildControls(parent);
				this.actionList = actionList ;
			}

			//	private Shell shell;
			private Table table;
			private TableViewer tableViewer;
			private Button closeButton;
			
			// Create a ExampleTaskList and assign it to an instance variable
			private java.util.List<com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction> actionList ; 

			// Set the table column property names
			private final String SELECTION_COLUMN 		= "!";
			private final String KIND_COLUMN 			= "kind";
			private final String ORIGINAL_COLUMN 		= "original feature";
			private final String SYNCHRONIZED_COLUMN 	= "synchronized feature";

			// Set column names
			private String[] columnNames = new String[] {
					SELECTION_COLUMN, 
					KIND_COLUMN,
					ORIGINAL_COLUMN,
					SYNCHRONIZED_COLUMN
					};

			/**
			 * Release resources
			 */
			public void dispose() {
				
				// Tell the label provider to release its ressources
				tableViewer.getLabelProvider().dispose();
			}

			/**
			 * Create a new shell, add the widgets, open the shell
			 * @return the shell that was created	 
			 */
			private void addChildControls(Composite composite) {

				// Create a composite to hold the children
				GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_BOTH);
				composite.setLayoutData (gridData);

				// Set numColumns to 3 for the buttons 
				GridLayout layout = new GridLayout(3, false);
				layout.marginWidth = 4;
				composite.setLayout (layout);

				// Create the table 
				createTable(composite);
				
				// Create and setup the TableViewer
				createTableViewer();
				tableViewer.setContentProvider(new ExampleContentProvider());
				tableViewer.setLabelProvider(new ExampleLabelProvider());
				// The input for the table viewer is the instance of ExampleTaskList
//				actionList = new ExampleTaskList();
				tableViewer.setInput(actionList);

				// Add the buttons
				createButtons(composite);
			}

			/**
			 * Create the Table
			 */
			private void createTable(Composite parent) {
				int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | 
							SWT.FULL_SELECTION | SWT.HIDE_SELECTION;

				final int NUMBER_COLUMNS = 4;

				table = new Table(parent, style);
				
				GridData gridData = new GridData(GridData.FILL_BOTH);
				gridData.grabExcessVerticalSpace = true;
				gridData.horizontalSpan = 3;
				table.setLayoutData(gridData);
							
				table.setLinesVisible(true);
				table.setHeaderVisible(true);

				// 1st column with image/checkboxes - NOTE: The SWT.CENTER has no effect!!
				TableColumn column = new TableColumn(table, SWT.CHECK, 0);	
				column.setText("!");
				column.setWidth(20);
				
				// 2nd column with task Description
				column = new TableColumn(table, SWT.LEFT, 1);
				column.setText("kind");
				column.setWidth(400);
				
				// 3rd column with task Owner
				column = new TableColumn(table, SWT.LEFT, 2);
				column.setText("original feature");
				column.setWidth(100);
				
				// 4th column with task PercentComplete 
				column = new TableColumn(table, SWT.CENTER, 3);
				column.setText("synchronized feature");
				column.setWidth(80);
				
			}

			/**
			 * Create the TableViewer 
			 */
			private void createTableViewer() {

				tableViewer = new TableViewer(table);
				tableViewer.setUseHashlookup(true);
				
				tableViewer.setColumnProperties(columnNames);

				// Create the cell editors
				CellEditor[] editors = new CellEditor[columnNames.length];

				// Column 1 : Completed (Checkbox)
				editors[0] = new CheckboxCellEditor(table);

				// Column 2 : Description (Free text)
				TextCellEditor textEditor = new TextCellEditor(table);
				((Text) textEditor.getControl()).setTextLimit(60);
				editors[1] = textEditor;

				// Column 3 : Owner (Combo Box) 
//				editors[2] = new ComboBoxCellEditor(table, actionList.getOwners(), SWT.READ_ONLY);
				editors[2] = textEditor;
				
				// Column 4 : Percent complete (Text with digits only)
				textEditor = new TextCellEditor(table);
				editors[3] = textEditor;
			}

			/*
			 * Close the window and dispose of resources
			 */
			public void close() {
				Shell shell = table.getShell();

				if (shell != null && !shell.isDisposed())
					shell.dispose();
			}


			/**
			 * InnerClass that acts as a proxy for the ExampleTaskList 
			 * providing content for the Table. It implements the ITaskListViewer 
			 * interface since it must register changeListeners with the 
			 * ExampleTaskList 
			 */
			class ExampleContentProvider implements IStructuredContentProvider, ITaskListViewer {
				public void inputChanged(Viewer v, Object oldInput, Object newInput) {
//					if (newInput != null)
//						((ExampleTaskList) newInput).addChangeListener(this);
//					if (oldInput != null)
//						((ExampleTaskList) oldInput).removeChangeListener(this);
				}

				public void dispose() {
//					actionList.removeChangeListener(this);
				}

				// Return the tasks as an array of Objects
				public Object[] getElements(Object parent) {
//					return actionList.getTasks().toArray();
					return null ;
				}

				/* (non-Javadoc)
				 * @see ITaskListViewer#addTask(ExampleTask)
				 */
				public void addTask(com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction action) {
					tableViewer.add(action);
				}

				/* (non-Javadoc)
				 * @see ITaskListViewer#removeTask(ExampleTask)
				 */
				public void removeTask(com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction action) {
					tableViewer.remove(action);			
				}

				/* (non-Javadoc)
				 * @see ITaskListViewer#updateTask(ExampleTask)
				 */
				public void updateTask(com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction action) {
					tableViewer.update(action, null);	
				}
			}
			
			/**
			 * Return the array of choices for a multiple choice cell
			 */
			public String[] getChoices(String property) {
				if (ORIGINAL_COLUMN.equals(property))
//					return actionList.getOwners();  // The ExampleTaskList knows about the choice of owners
					return null ;
				else
					return new String[]{};
			}

			/**
			 * Add the "Add", "Delete" and "Close" buttons
			 * @param parent the parent composite
			 */
			private void createButtons(Composite parent) {
				
				// Create and configure the "Add" button
				Button add = new Button(parent, SWT.PUSH | SWT.CENTER);
				add.setText("Add");
				
				GridData gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
				gridData.widthHint = 80;
				add.setLayoutData(gridData);
//				add.addSelectionListener(new SelectionAdapter() {
//		       	
//		       		// Add a task to the ExampleTaskList and refresh the view
//					public void widgetSelected(SelectionEvent e) {
//						actionList.addTask();
//					}
//				});

				//	Create and configure the "Delete" button
				Button delete = new Button(parent, SWT.PUSH | SWT.CENTER);
				delete.setText("Delete");
				gridData = new GridData (GridData.HORIZONTAL_ALIGN_BEGINNING);
				gridData.widthHint = 80; 
				delete.setLayoutData(gridData); 

//				delete.addSelectionListener(new SelectionAdapter() {
//		       	
//					//	Remove the selection and refresh the view
//					public void widgetSelected(SelectionEvent e) {
//						ExampleTask task = (ExampleTask) ((IStructuredSelection) 
//								tableViewer.getSelection()).getFirstElement();
//						if (task != null) {
//							actionList.removeTask(task);
//						} 				
//					}
//				});
				
				//	Create and configure the "Close" button
				closeButton = new Button(parent, SWT.PUSH | SWT.CENTER);
				closeButton.setText("Close");
				gridData = new GridData (GridData.HORIZONTAL_ALIGN_END);
				gridData.widthHint = 80; 
				closeButton.setLayoutData(gridData); 		
			}

			/**
			 * Return the column names in a collection
			 * 
			 * @return List  containing column names
			 */
			public java.util.List getColumnNames() {
				return Arrays.asList(columnNames);
			}

			/**
			 * @return currently selected item
			 */
			public ISelection getSelection() {
				return tableViewer.getSelection();
			}

			/**
			 * Return the ExampleTaskList
			 */
//			public ExampleTaskList getTaskList() {
//				return actionList;	
//			}

			/**
			 * Return the parent composite
			 */
			public Control getControl() {
				return table.getParent();
			}

			/**
			 * Return the 'close' Button
			 */
			public Button getCloseButton() {
				return closeButton;
			}
		}
	
	public interface ITaskListViewer {
		
		/**
		 * Update the view to reflect the fact that a task was added 
		 * to the task list
		 * 
		 * @param task
		 */
		public void addTask(com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction task);
		
		/**
		 * Update the view to reflect the fact that a task was removed 
		 * from the task list
		 * 
		 * @param task
		 */
		public void removeTask(com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction task);
		
		/**
		 * Update the view to reflect the fact that one of the tasks
		 * was modified 
		 * 
		 * @param task
		 */
		public void updateTask(com.cea.papyrus.umlutils.TemplateableElement.SynchronizationAction task);
	}
}
